package valuetypes;
import java.util.Arrays;

import exception.DBValueException;


public class DBValue {
	
	protected int size;
	protected byte[] data;
	
	protected DBValue(int size){
		this.size = size;
		data = new byte[size];
	}
	
	public DBValue(byte[] data, int offset){
		
	}
	
	protected DBValue(int size, byte[] data2, int offset) throws DBValueException {
		this.size= size;
		int start = offset;
		int end = size + offset;
		try{
			byte[] valueData = Arrays.copyOfRange(data2, start, end);  //lekker consistent?
			setData(valueData);
		}
		catch(ArrayIndexOutOfBoundsException ex){
			throw ex;
		}
		
		
	}

	public int getSize(){
		return size;
	}
	
	public void setData(byte[] data) throws DBValueException{
		//TODO check length
		if(data.length != size)throw DBValueException.dataSizeMisMatch(size, data.length);
		byte[] oldData = this.data;
		this.data = data;
		onDataChanged(oldData, this.data);
	}
	
	public byte[] getData(){
		return data;
	}
	
	/***
	 * Function called after data has changed
	 * @param oldData a copy of the previous data array
	 * @param newData the new data array
	 */
	protected void onDataChanged(byte[] oldData, byte[] newData){
		//Implemented in subclasses, so do nothing here.
	}

	public boolean isNull() {
		return data == null;
	}
	
	public static byte[] valuesAsData(DBValue...dbValues ){
		int totalLength = 0;
		for(DBValue v : dbValues){
			totalLength += v.size;
		}
		byte[] out = new byte[totalLength];
		int offset = 0;
		for(DBValue v : dbValues){			
			System.arraycopy(v.data, 0, out, offset, v.size);
			offset += v.size;
		}
		return out;
	}
	
	

}
